import { parseTime } from '@/utils'
import { formatTime } from '@/utils/date-parse'

/**
 * json数据导出excel公共方法
 * @param {Object} headerData：表头数据 示例：['昵称', '电话', ...];
 * @param {Object} tableData：表格数据 示例：[];
 * @param {Object} filterData：取值字段名称 示例：['nickname', 'phoneNumber', ...];
 * @param {Object} fileName：导出Excel的文件名
 */
export function export2Excel(headerData, tableData, filterData, fileName, callback) {
  import('@/vendor/Export2Excel').then(excel => {
    const tHeader = headerData
    const filterVal = filterData
    const filename = fileName
    const list = tableData ? tableData : []
    const data = formatJson(filterVal, list)

    excel.export_json_to_excel({
      header: tHeader,
      data,
      filename: filename,
      autoWidth: true,
      bookType: 'xlsx'
    })
    if (callback) {
      callback()
    }
  })
}

/**
 *合并单元格
 * @param headerData
 * @param tableData
 * @param filterData
 * @param fileName
 * @param callback
 */
export function export2TreeExcel(headerData, tableData, filterData, fileName, merges, callback) {
  import('@/vendor/Export2Excel').then(excel => {
    const tHeader = headerData
    const filterVal = filterData
    const filename = fileName
    const list = tableData ? tableData : []
    const data = formatJson(filterVal, list)
    excel.export_json_to_tree_excel(tHeader, data, filename, merges)
    if (callback) {
      callback()
    }
  })
}

function formatJson(filterVal, jsonData) {
  return jsonData.map(v =>
    filterVal.map(j => {
      if (j === 'timestamp') {
        return parseTime(v[j])
      } else {
        return v[j]
      }
    })
  )
}

/**
 * 文件流数据导出Excel公共方法
 * @param {Object} fileStream 文件IO流
 * @param {Object} fileName 文件名称
 * @param {Object} suffix 文件后缀名：例如 xls
 * @param {Object} callback 回调方法
 */
export function export2ExcelFromFileStream(fileStream, fileName, suffix, callback) {
  let blob = new Blob([fileStream], {
    type: 'application/vnd.ms-excel;charset=utf-8'
  })
  let url = window.URL.createObjectURL(blob)
  let aLink = document.createElement('a')
  aLink.style.display = 'none'
  aLink.href = url
  if (suffix) {
    let exportDate = formatTime(new Date()).replace(/\//g, '').replace(/\s/g, '').replace(/:/g, '')
    aLink.download = fileName + '_' + exportDate + '.' + suffix
  } else {
    aLink.download = fileName
  }
  document.body.appendChild(aLink)
  aLink.click()

  window.URL.revokeObjectURL(aLink.href)
  document.body.removeChild(aLink)
  if (callback) {
    callback()
  }
}
